package sapling.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sapling.aop.WebLogAspect;
import sapling.dao.LogDao;
import sapling.model.Log;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by Administrator on 2017/6/21.
 */
@Service
@Transactional
public class LogService {

    private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Autowired
    LogDao logDao;

    /**
     * 保存日志
     * @param operation
     */
    public void saveLog(String operation) {
        Subject currentUser = SecurityUtils.getSubject();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String username = currentUser.getSession().getAttribute("username").toString();
        Log log = new Log();
        log.setUsername(username);
        log.setURL(request.getRequestURL().toString());
        log.setOperation(operation);
        if ("0:0:0:0:0:0:0:1".equals(request.getRemoteAddr())) {
            log.setIP("127.0.0.1");
        } else {
            log.setIP(request.getRemoteAddr());
        }
        log.setOperationtime(new Date());
        logDao.save(log);
    }
}
